#!/usr/bin/env python3
#-*- coding:utf-8 -*-

'''
文件名称：main.py
创 建 者：yang qiang
创建日期：2019年02月19日
描    述：
Copyright (C) 2019 All rights reserved.
'''

import sys
import math 

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        length = len(nums)
        start = 0
        end = length - 1
        closedif = sys.maxint
        sum = 0

        for i in range(0, length):
            start = i + 1
            end = length - 1
            while start < end:
                tmpsum = nums[i] + nums[start] + nums[end]
                tmpdif = abs(target - tmpsum)
                if tmpdif < closedif:
                    closedif = tmpdif
                    sum = tmpsum

                if target - tmpsum > 0:
                    start = start + 1
                elif target - tmpsum < 0:
                    end = end - 1
                else:
                    return sum

        return sum
